//
//  BirthdayTableViewController.swift
//  BirthdayManager
//
//  Created by Apple on 2020/12/16.
//  Copyright © 2020 Charles. All rights reserved.
//

import UIKit

class BirthdayTableViewController: UITableViewController {
    var birthdays = [birthday]()
    func saveBirthday(){
        let success = NSKeyedArchiver.archiveRootObject(birthdays, toFile: birthday.userPath)
        if !success{
            print("fail to save birthday...")
        }
    }
    func loadBirthday() {
        if let birthday = NSKeyedUnarchiver.unarchiveObject(withFile: birthday.userPath) as? [birthday]{
            birthdays = birthday
            print("load file successfully")
        }else{
            print("load failed")
        }
    }
    func initialBirthdayList() ->Void {
        birthdays.append(birthday(name: "user1", date: "2000-6-7", count: "10", avatar: nil))
//        birthdays.append(birthday(name: "user2", date: "2020-12-12", count: "10", avatar: nil))
//        birthdays.append(birthday(name: "user3", date: "2020-12-12", count: "10", avatar: nil))
        
    }
    @IBAction func saveToList(segue: UIStoryboardSegue){
        if let sourceVC = segue.source as? BirthdayViewController,let birthday = sourceVC.birthdayForEdit{
            if let selectedIndex = tableView.indexPathForSelectedRow{
                birthdays[selectedIndex.row] = birthday
                tableView.reloadRows(at: [selectedIndex], with: UITableView.RowAnimation.automatic)
            }else{
                birthdays.append(birthday)
                tableView.reloadData()
            }
            saveBirthday()
        }
    }
    @IBAction func cancel(segue:UIStoryboardSegue){
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.rowHeight = 80
        loadBirthday()
        if(birthdays.isEmpty){
            initialBirthdayList()
        }
        
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }
    

    // MARK: - Table view data source
    // 分组数量
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return birthdays.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "birthdayCell", for: indexPath) as! BirthdayViewCellController

        // Configure the cell...
        cell.nameLabel?.text = birthdays[indexPath.row].name
        //cell的style改成subtitle然后添加下面内容
        cell.dateLabel?.text = birthdays[indexPath.row].date
        cell.countLabel?.text = "距离ta的生日还有" +  birthdays[indexPath.row].count + "天"
        cell.avatarImage?.image = birthdays[indexPath.row].avatar
        return cell
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            birthdays.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            saveBirthday()
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if let destVC = segue.destination as?BirthdayViewController{
            if let selectedIndex = tableView.indexPathForSelectedRow?.row{
                destVC.birthdayForEdit =
                    birthdays[selectedIndex]
            }
        }
    }
    
    //陈泽钧：本地通知功能
    var daylist: [dayinfo] = [dayinfo]()
    
    func loadAnniversary() {
        if let days = NSKeyedUnarchiver.unarchiveObject(withFile: dayinfo.userPath) as? [dayinfo] {
            daylist = days
            print("load file successful")
        }
    }
    
    func printAnniversary(){
        var numlist: [Int]
        numlist = []
        if daylist.count > 0{
        for i in 0...(daylist.count - 1){
            let calendar = Calendar.current.dateComponents(in :TimeZone.current, from: daylist[i].date!)//date无法直接进行比较，所以先转化成dateComponent
            let today = Calendar.current.dateComponents(in :TimeZone.current, from: Date())//将今天的dataComponents复制到today中
            
            if calendar.month == today.month && calendar.day == today.day{
                numlist.append(i)
            }//如果他们的日期相同的话就将下标传递给numlist中
            
        }
            //print(numlist[0])
          
        }//至此获得了numlist数组
        if numlist.count == 1{
            scheduleNotification(itemID: numlist[0],num: 0)
        }
        else if numlist.count > 1{
            for i in 0...(numlist.count-1){
                scheduleNotification(itemID: numlist[i], num: Double(i))
            }
        }
        numOfPrintedAnniversary = Double(numlist.count)//为了方便待会按照顺序发出推送
    }
    
    func scheduleNotification(itemID:Int,num:Double){
            //如果已存在该通知消息，则先取消
            cancelNotification(itemID: itemID)
            //创建UILocalNotification来进行本地消息通知
            let localNotification = UILocalNotification()
            //推送时间（设置为立刻）
        localNotification.fireDate = NSDate(timeIntervalSinceNow: (5+num*5)) as Date
            //时区
        localNotification.timeZone = NSTimeZone.default
            //推送内容
        localNotification.alertBody = "今天是" + daylist[itemID].dayname!
            //声音
            localNotification.soundName = UILocalNotificationDefaultSoundName
            localNotification.userInfo = ["ItemID":itemID]
        UIApplication.shared.scheduleLocalNotification(localNotification)
        }
    
         
        //取消通知消息
        func cancelNotification(itemID:Int){
            //通过itemID获取已有的消息推送，然后删除掉，以便重新判断
            let existingNotification = self.notificationForThisItem(itemID: itemID) as UILocalNotification?
            if existingNotification != nil {
                //如果existingNotification不为nil，就取消消息推送
                UIApplication.shared.cancelLocalNotification(existingNotification!)
            }
        }
         
        //通过遍历所有消息推送，通过itemid的对比，返回UIlocalNotification
        func notificationForThisItem(itemID:Int)-> UILocalNotification? {
            let allNotifications = UIApplication.shared.scheduledLocalNotifications
            for notification in allNotifications! {
                let info = notification.userInfo as! [String:Int]
                let number = info["ItemID"]
                if number != nil && number == itemID {
                    return notification as UILocalNotification
                }
            }
            return nil
        }
    
    func printBirthday(){
        var numlist: [Int]
        numlist = []
        if birthdays.count > 0{
        for i in 0...(birthdays.count - 1){
            var temp:String = birthdays[i].computeCount(dateString: birthdays[i].date)
            let calendar = Calendar.current.dateComponents(in :TimeZone.current, from: birthdays[i].dayFormat!)//date无法直接进行比较，所以先转化成dateComponent
            let today = Calendar.current.dateComponents(in :TimeZone.current, from: Date())//将今天的dataComponents复制到today中
            
            if calendar.month == today.month && calendar.day == today.day{
                numlist.append(i)
            }//如果他们的日期相同的话就将下标传递给numlist中
            
        }
            //print(numlist[0])
          
        }//至此获得了numlist数组
        if numlist.count == 1{
            scheduleNotificationForBirthdays(itemID: numlist[0]+1000,num: 0)//+1000是因为要和周年的itemID区分开
        }
        else if numlist.count > 1{
            for i in 0...(numlist.count-1){
                scheduleNotificationForBirthdays(itemID: numlist[i]+1000, num: Double(i))
            }
        }
    }
    
    func scheduleNotificationForBirthdays(itemID:Int,num:Double){
            //如果已存在该通知消息，则先取消
            cancelNotification(itemID: itemID)
            //创建UILocalNotification来进行本地消息通知
            let localNotification = UILocalNotification()
            //推送时间（设置为立刻）
        localNotification.fireDate = NSDate(timeIntervalSinceNow: (5+numOfPrintedAnniversary*5+num*5)) as Date
        print(numOfPrintedAnniversary)
            //时区
        localNotification.timeZone = NSTimeZone.default
            //推送内容
        localNotification.alertBody = "今天是" + birthdays[itemID-1000].name + "的生日"
            //声音
            localNotification.soundName = UILocalNotificationDefaultSoundName
            localNotification.userInfo = ["ItemID":itemID]
        UIApplication.shared.scheduleLocalNotification(localNotification)
        }
    
    var numOfPrintedAnniversary: Double = 0
    
    override func loadView() {
        super.loadView()
        loadAnniversary()
        printAnniversary()
        loadBirthday()
        printBirthday()
    }

}
